#include <rtthread.h>
#include <stdint.h>
#include <string.h>
#include "read_uid.h"
#include "util.h"

// Raw variables
static uint32_t host_id[4];

static char string_unique_id[48 + 1];
static char string_host_id[32 + 1];

static char usb_desc_unique_id[2 + sizeof(string_unique_id) * 2];

const char *info_get_unique_id_string_descriptor(void)
{
    return usb_desc_unique_id;
}

static void setup_basics(void)
{
    uint8_t i = 0, idx = 0;

    memset(string_host_id, 0, sizeof(string_host_id));

    for (i = 0; i < 4; i++)
    {
        idx += util_write_hex32(string_host_id + idx, host_id[i]);
    }
}

static void setup_unique_id()
{
    memset(string_unique_id, 0, sizeof(string_unique_id));
    strcat(string_unique_id, string_host_id);
}

static void setup_string_descriptor()
{
    uint8_t i = 0, idx = 0, len = 0;
    len = strlen((const char *)string_unique_id);
    // bLength
    usb_desc_unique_id[idx++] = len * 2 + 2;
    // bDescriptorType
    usb_desc_unique_id[idx++] = 3;

    // bString
    for (i = 0; i < len; i++)
    {
        usb_desc_unique_id[idx++] = string_unique_id[i];
        usb_desc_unique_id[idx++] = 0;
    }
}

int info_init(void)
{
    read_unique_id(host_id);
    setup_basics();
    setup_unique_id();
    setup_string_descriptor();
    return 0;
}
INIT_PREV_EXPORT(info_init);
